package com.bruan.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bruan.pojo.Result;
import com.bruan.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求url
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String url = httpServletRequest.getRequestURL().toString();
        log.info("请求的URL{}",url);
        //请求url中是否包含login 如果包含就放行
        if(url.contains("login")){
            log.info("login-放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //获取请求头的令牌token
        String jwt = httpServletRequest.getHeader("token");
        // 判断令牌是否存在
        if (!StringUtils.hasLength(jwt)){
            //null
            log.info("jwt为空");
            Result error = Result.error("NOT_LOGIN");
            //手动转换 对象 --》 阿里巴巴fastjson
            String jsonString = JSONObject.toJSONString(error);
            //响应给外部
            httpServletResponse.getWriter().write(jsonString);
            return;
        };
        //解析token类
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败");
            Result error = Result.error("NOT_LOGIN");
            String error1 = JSONObject.toJSONString(error);
            httpServletResponse.getWriter().write(error1);
            return;
        }

        //放行
        log.info("令牌合法");
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
